import axios from 'src/utils/http'
// import qs from 'qs'

export interface registerForm {
  username: string;
  email: string;
  password: string;
}

export interface loginForm {
  email: string;
  password: string;
}

export interface profileFormProps {
  image: string;
  username: string;
  bio: string;
  email: string;
  password: string;
}

type returnType = {
  msg: string,
  errors?: Record<string, string[]>
}

export async function postRegister (form: registerForm): Promise<returnType> {
  let result: returnType = { msg: '' }
  try {
    await axios.post(`/users`, JSON.stringify({ user: form }))
    result = { msg: 'success' }
  } catch (error) {
    const { response } = error
    if (response.status === 422) {
      result = { msg: 'fail', errors: response.data.errors }
    }
  }
  return result
}

type loginReturnType = {
  msg: string,
  data?: object
}

export async function postLogin (form: loginForm): Promise<loginReturnType> {
  let result: loginReturnType = { msg: '' }
  try {
    let res = await axios.post(`/users/login`, JSON.stringify({ user: form }))
    result = { msg: 'success', data: res.data.user }
  } catch (error) {
    const { response } = error
    if (response.status === 422) {
      result = { msg: 'fail' }
    }
  }
  return result
}

export async function putProfile (form: profileFormProps) {
  console.log(JSON.stringify(form))
  await axios.put(`/user`, JSON.stringify(form))
}